#include <bits/stdc++.h>
using namespace std;
const int maxn = 10000+10;
int l[maxn], r[maxn], root;
int best, bestsum, N;
int in[maxn], po[maxn];

void dfs(int ro, int sum){
    sum += ro;
    if(!l[ro] && !r[ro]){
        if(sum < bestsum || (sum == bestsum && ro < best)){
            bestsum = sum; best = ro;
        }
    }
    if(l[ro]) dfs(l[ro], sum);
    if(r[ro]) dfs(r[ro], sum);
}

int build(int L1, int R1, int L2, int R2){
    if(L1 > R1) return 0;
    int ro = po[R2];
    int p = 0;
    for (int i = L1; i <= R1; ++i) {
        if(in[i] == ro) {p = i; break;}
    }
    int lcnt = p-L1;
    l[ro] = build(L1, p-1, L2, L2+lcnt-1);
    r[ro] = build(p+1, R1, L2+ lcnt, R2-1);
    return ro;
}

int main() {
    //ios_base::sync_with_stdio(false);cin.tie(nullptr);
    string sin, spost;
    while(getline(cin, sin) && getline(cin, spost)){
        memset(l, 0, sizeof(l)); memset(r, 0, sizeof(r));
        stringstream ss;
        ss.str(sin); N = 0; while(ss >> in[N++]);
        ss.clear();
        ss.str(spost); N = 0; while(ss >> po[N++]);
        --N;
        best = INT_MAX; bestsum = INT_MAX;
        root = build(0, N-1, 0, N-1);
        dfs(root, 0);
        cout << best << '\n';
    }
    return 0;
}